import { Injectable } from '@nestjs/common';
import { CreateProcessTemplateDto } from './dto/create-process-template.dto';
import { UpdateProcessTemplateDto } from './dto/update-process-template.dto';
import { CrudService } from '../../common/crud/crud.service';
import { PrismaService } from 'nestjs-prisma';

@Injectable()
export class ProcessTemplateService extends CrudService {
  constructor(readonly prisma: PrismaService) {
    super(prisma, 'processTemplate');
  }

  findOne(id: string) {
    return this.prisma.processTemplate.findUnique({
      where: {
        id,
      },
      include: {
        prices: {
          select: {
            sizeId: true,
            price: true,
          },
        },
      },
    });
  }

  create(createProcessTemplateDto: CreateProcessTemplateDto) {
    const prices = createProcessTemplateDto.prices;
    delete createProcessTemplateDto.prices;

    return this.prisma.processTemplate.create({
      data: {
        name: createProcessTemplateDto.name,
        description: createProcessTemplateDto.description,
        prices: {
          createMany: {
            data: prices,
          },
        },
      },
    });
  }

  update(id: string, updateProcessTemplateDto: UpdateProcessTemplateDto) {
    const prices = updateProcessTemplateDto.prices;
    delete updateProcessTemplateDto.prices;

    return this.prisma.processTemplate.update({
      where: { id },
      data: {
        name: updateProcessTemplateDto.name,
        description: updateProcessTemplateDto.description,
        prices: {
          deleteMany: {},
          createMany: {
            data: prices,
          },
        },
      },
    });
  }

  async remove(id: string) {
    const deletePrices = this.prisma.processTemplatePrice.deleteMany({
      where: {
        processTemplateId: id
      }
    })

    const del = this.prisma.processTemplate.delete({
      where: {
        id: id
      }
    })
    await this.prisma.$transaction([deletePrices, del])

    return 'ok'
  }
}
